package psn.kiko.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import psn.kiko.constant.MessageConstant;
import psn.kiko.constant.ResponseCodeConstant;
import psn.kiko.excepion.ApiAuthorityException;
import psn.kiko.excepion.BaseBusinessException;
import psn.kiko.pojo.Result;

/**
 * 全局异常处理器<br>
 * 程序的其它地方不需要再处理异常，只需要直接抛出异常
 */
@ControllerAdvice(basePackages = "psn.kiko.controller")
@ResponseBody
@Slf4j
public class GlobalExceptionHandler{
	
	//拦截自定义业务异常
	@ExceptionHandler(value = {BaseBusinessException.class})
	public Result handleBusinessException(BaseBusinessException exception){
		if(log.isDebugEnabled()){
			log.debug("开始拦截处理自定义异常: {}: {}",exception.getClass().getName(),exception.getMessage());
		}
		if(exception instanceof ApiAuthorityException){
			return Result.builder()
					.code(ResponseCodeConstant.BUSINESS_OPERATION_FAIL)
					.data(exception.getMessage())
					.msg(exception.getMessage())
					.build();
		}else if(exception instanceof BaseBusinessException){
			return Result.builder()
					.code(ResponseCodeConstant.BUSINESS_OPERATION_FAIL)
					.data(exception.getMessage())
					.msg(exception.getMessage())
					.build();
		}else{
			return Result.builder()
					.code(ResponseCodeConstant.BUSINESS_OPERATION_FAIL)
					.data(exception.getMessage())
					.msg(MessageConstant.UNKNOWN_ERROR)
					.build();
		}
	}
	
	//拦截非自定义的异常
	@ExceptionHandler(value = {Exception.class})
	public Result handleNoneBusinessException(Exception exception){
		if(log.isDebugEnabled()){
			log.debug("开始处理非自定义异常:{} : {}",exception.getClass().getName(),exception.getMessage());
		}
		exception.printStackTrace();
		return Result.fail(MessageConstant.UNKNOWN_ERROR,exception.getMessage());
	}
}
